<template>
  <div class="page_main">
    <div class="header">{{ is_created ? '安装工单新增页' : '安装工单编辑页' }}</div>
    <el-form ref="cuForm" :model="cuForm" :rules="rule" label-width="80px" label-position="right"
             v-loading="formLoading" :disabled="formDisabled"
    >
      <el-divider>基本信息</el-divider>
      <el-row style="padding-top: 20px">
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="cuForm.name" style="max-width: 500px;width: 100%" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="work_order_type_id">
            <el-radio-group v-model="cuForm.work_order_type_id" :disabled="edit"
                            @change="workOrderTypeChange"
            >
              <el-radio :label="2">上刊</el-radio>
              <el-radio :label="3">下刊</el-radio>
              <el-radio :label="4">巡检</el-radio>
              <el-radio :label="1">新安装</el-radio>
              <el-radio :label="7">换画</el-radio>
              <el-radio :label="8">中间监播</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止时间" prop="deadline" style="position: relative">
            <span style="color: #e54d42;font-size: 14px;position: absolute;top: -30px;"
            >超出截止时间的工单，对工人不可见，请慎重配置！</span>
            <el-date-picker
              v-model="cuForm.deadline"
              type="datetime"
              placeholder="选择工单截止时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="max-width: 500px;width: 100%"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="cuForm.remark" type="textarea" style="max-width: 500px;width: 100%" placeholder="请输入备注"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-show="cuForm.work_order_type_id==4">
        <el-form-item label="来源">
          <el-radio-group v-model="type" :disabled="edit" @change="typeChange">
            <el-radio label="1">销售单</el-radio>
            <el-radio label="2">楼盘</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div>
        <el-form-item>
          <el-button style="margin-left: 0" v-show="(type == 2&&this.buildingList.length == 0)&&!edit" type="primary"
                     size="mini"
                     @click="showBuildingDialog"
          >
            关联楼盘
          </el-button>
          <el-button style="margin-left: 0" v-show="(type == 1&&this.tmpList.length==0)&&!edit" type="primary"
                     size="mini"
                     @click="showSaleOrderDialog"
          >关联销售单
          </el-button>
        </el-form-item>
      </div>
    </el-form>
    <div>
      <div style="text-align: right">
        <el-button v-show="selectBuildingIdList.length>0" style="margin-right: 40px" type="primary" size="mini"
                   @click="showAssignWorkers"
        >分配工人
        </el-button>
      </div>
      <!--普通楼盘配置-->
      <el-table
        v-if="((cuForm.work_order_type_id == 4&&type==2) || cuForm.work_order_type_id == 1)&&buildingList.length>0"
        :data="buildingList" size="mini" row-class-name="building" header-row-class-name="building_header"
        style="margin-top: 20px"
      >
        <el-table-column label="楼盘" width="300" align="center" prop="name"></el-table-column>
        <el-table-column label="点位" min-width="200" align="center">
          <template slot-scope="scope">
            <div style="display: inline-block" v-for="item in scope.row.media_point" :key="item.media_type_id">
              <span>{{ item.name }}</span>
              <div>
                <el-input-number v-model="item.select_num" :min="item.num" :disabled="item.disabled" size="mini"
                ></el-input-number>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工人" width="150" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{
              scope.row.works.map(item => {
                return item.name
              }).join(',')
            }}
          </template>
        </el-table-column>
      </el-table>
      <!--工单楼盘配置-->
      <point-config
        v-if="((cuForm.work_order_type_id == 4&&type == 1) || cuForm.work_order_type_id == 2||cuForm.work_order_type_id == 3||cuForm.work_order_type_id == 7||cuForm.work_order_type_id == 8)&&tmpList.length>0"
        :read-only="true"
        style="width: 100%" :data="tmpList" :is-work-order-show="true" :work-order-id="cuForm.id"
        :is-replace="cuForm.work_order_type_id == 2&&!is_created&&cuForm.mode != 1&&cuForm.mode != 2 "
        @replace="replacePoint" @reload="reload"
      ></point-config>
    </div>
    <div style="text-align: center;margin-top: 20px">
      <el-button @click="closeThisPage">取消</el-button>
      <el-button v-show="!formDisabled" type="primary" @click="save">保存</el-button>
    </div>

    <!--销售单弹框-->
    <el-dialog title="关联销售单" center width="80%" :visible.sync="centerDialogVisible" @close="closeSaleOrderDialog">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-divider>可选销售单</el-divider>
          <div class="search-box">
            <el-form :inline="true" size="mini" :model="saleOrderSearchForm" ref="searchForm">
              <search-form-box :show-more-btn="false">
                <template slot="showSearch">
                  <el-form-item label="销售单甲方：" prop="name">
                    <el-input v-model="saleOrderSearchForm.name" placeholder="请输入销售单甲方" clearable></el-input>
                  </el-form-item>
                </template>
                <template slot="searchBtn">
                  <el-form-item>
                    <el-button type="primary" @click="getSaleOrderList">查询</el-button>
                    <el-button @click="resetSaleOrderForm">重置</el-button>
                  </el-form-item>
                </template>
              </search-form-box>
            </el-form>
          </div>
          <el-table :data="saleOrderTableData" v-loading="saleOrderTableLoading" border size="mini" stripe>
            <el-table-column type="index" label="序号" width="50" align="center">
              <template slot-scope="scope">
                <span>{{ (saleListParams.page - 1) * saleListParams.page_size + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="销售单" align="center" min-width="250" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.name + '   ' + scope.row.start_at + '~' + scope.row.end_at }}</span>
              </template>
            </el-table-column>
            <el-table-column label="关联工单" align="center" min-width="400" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-for="item in scope.row.workOrderList" :key="item.id">
                  <el-tag v-if="item.work_order_type_id == 2" size="mini">上刊{{ '——' + item.name }}</el-tag>
                  <el-tag v-if="item.work_order_type_id == 3" size="mini" type="danger">下刊{{
                      '——' + item.name
                    }}
                  </el-tag>
                  <el-tag v-if="item.work_order_type_id == 4" size="mini" type="warning">巡检{{
                      '——' + item.name
                    }}
                  </el-tag>
                  <el-tag v-if="item.work_order_type_id == 7" size="mini" type="info">换画{{ '——' + item.name }}</el-tag>
                  <el-tag v-if="item.work_order_type_id == 8" size="mini" type="success">中间监播{{
                      '——' + item.name
                    }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="selectOrder(scope.row)">选中
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @current-change="saleTableCurrentChange"
            :current-page.sync="saleListParams.page"
            :page-size="10"
            layout="total, prev, pager, next"
            :total="saleTableTotal"
          >
          </el-pagination>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-divider>选择的销售单</el-divider>-->
        <!--          <el-table :data="selectOrderTableData" border size="mini" stripe>-->
        <!--            <el-table-column label="序号" width="50" align="center">-->
        <!--              <template slot-scope="scope">-->
        <!--                {{ scope.$index + 1 }}-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--            <el-table-column label="销售单" align="center" min-width="350" show-overflow-tooltip>-->
        <!--              <template slot-scope="scope">-->
        <!--                <span>{{ scope.row.name + '   ' + scope.row.start_at + '~' + scope.row.end_at }}</span>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--            <el-table-column label="操作" align="center" width="100">-->
        <!--              <template slot-scope="scope">-->
        <!--                <el-button type="danger" size="mini" @click="removeOrder(scope.$index)">移除</el-button>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--          </el-table>-->
        <!--        </el-col>-->
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="centerDialogVisible = false">取 消</el-button>
        <!--        <el-button size="mini" type="primary" @click="chooseSaleOrder">确 定</el-button>-->
      </span>
    </el-dialog>
    <!--楼盘选择-->
    <el-dialog title="关联楼盘" :visible.sync="buildingDialogVisible" width="90%" center
               @close="closeBuildingDialog"
    >
      <el-row :gutter="40">
        <el-col :span="12">
          <el-divider>可选楼盘</el-divider>
          <el-form :inline="true" size="mini">
            <el-form-item label="楼盘">
              <el-input v-model.trim="buildingSearchForm.name" clearable placeholder="请输入楼盘名称"></el-input>
            </el-form-item>
            <el-form-item label="区域：" prop="adcode">
              <el-select clearable v-model="buildingSearchForm.adcode" filterable placeholder="请选择区域"
                         style="width:100%"
              >
                <el-option v-for="item in searchAreaVOList" :key="item.adcode" :label="item.area" :value="item.adcode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-show="buildingSearchForm.work_order_type_id !== 1" label="媒体类型：" prop="media_type_id">
              <el-select clearable v-model="buildingSearchForm.media_type_id" filterable placeholder="请选择媒体类型"
                         style="width:100%"
              >
                <el-option v-for="item in media_type_arr" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain size="mini" @click="buildingSearch">搜索</el-button>
              <el-button v-show="buildingSearchForm.work_order_type_id !== 1" type="primary" size="mini"
                         @click="allSelect"
              >全选
              </el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="buildingTableLoading" :data="buildingTableData" border row-key="id">
            <el-table-column type="index" label="序号" width="50" align="center">
              <template slot-scope="scope">
                <span>{{ (buildingListParams.page - 1) * buildingListParams.page_size + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="地址" prop="name" align="center" min-width="300" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="点位" align="center" width="200" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-for="item in scope.row.media_point" :key="item.media_type_id">
                    {{ item.name + (item.num != undefined ? (item.num + '个') : (item.point_ids.length + '个')) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <el-button type="primary" size="small"
                           :disabled="selectBuildingTableData.find(item=>item.id==scope.row.id)!=undefined"
                           @click="selectBuilding(scope.row)"
                >选中
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="buildingSearchForm.page"
            :page-size.sync="buildingSearchForm.page_size"
            layout="total,prev, pager, next, jumper"
            :total="buildingTotal"
            @current-change="buildingTableCurrentChange"
          />
        </el-col>
        <el-col :span="12">
          <el-divider>选中楼盘</el-divider>
          <div v-show="buildingSearchForm.work_order_type_id !== 1" style="text-align: right;margin-bottom: 10px">
            <el-button size="mini" type="danger"
                       :disabled="!selectBuildingTableData || (selectBuildingTableData && selectBuildingTableData.length===0)"
                       @click="allRemoveBuilding"
            >全部移除
            </el-button>
          </div>
          <el-table :data="selectBuildingTableData" border max-height="618" tooltip-effect="dark"
                    style="width: 100%;overflow-y: auto" highlight-current-row row-key="id"
          >
            <el-table-column type="index" label="序号" width="50" align="center">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="name" align="center" min-width="300" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="点位" align="center" width="200" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-for="item in scope.row.media_point" :key="item.media_type_id">
                    {{ item.name + (item.num != undefined ? (item.num + '个') : (item.point_ids.length + '个')) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="removeBuilding(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="buildingDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="chooseBuilding">确 定</el-button>
      </span>
    </el-dialog>
    <building-tree :show="assignWorkersDialogVisible" :tree-data="treeData" @close="closeAssignWorkersDialog"
                   @save="saveAssignWorkers"
    ></building-tree>
  </div>
</template>
<script>
import {
  allSelectBuildingList,
  detail,
  edit,
  listBillSale,
  listBuildingMacthWorker,
  listBuildingOfBillSale,
  listPageBuilding,
  replacePoint,
  save
} from '@/api/workOrder/workOrder'
import pointConfig from '@/components/PointPlanSetting/pointConfig'
import buildingTree from './components/buildingTree'
import { formatDataToSale, getBuildingWorkers } from '@/views/business/contract/util'
import { generateUUID } from '@/utils/util'
import common from '@/utils/common'
import { get_media_types, selectSearchAreaVO } from '@/api/building/building'
import { cloneDeep } from 'lodash'
import SearchFormBox from '@/components/SearchFormBox'

export default {
  name: 'edit',
  components: {
    pointConfig,
    buildingTree,
		SearchFormBox
  },
  computed: {
    selectBuildingIdList() {
      if (this.type == 1) {
        if (this.tmpList.length > 0) {
          return this.tmpList[0].dataArr.map(item => {
            return item.id
          })
        } else {
          return []
        }
      } else {
        return this.buildingList.map(item => {
          return item.id
        })
      }
    },
    formDisabled() {
      console.log(this.cuForm.mode)
      return this.cuForm.mode == 1
    }
  },
  created() {
    const params = this.$route.params
    if (params) {
      if (params.is_created) {
        this.is_created = params.is_created
      }
      if (params.id) {
        this.getDetail(params)
      }
    }
    this.selectSearchArea()
    this.initMediaTypeArr()
  },
  data() {
    return {
      is_created: false,
      edit: false,
      formLoading: false,
      cuForm: {
        id: null,
        work_order_type_id: 2,
        name: null,
        deadline: null,
        remark: null,
        bill_sale_id: null,
        bill_market_detail_id: 0,
        buidingSaveDTOS: [],
        mode: null
      },
      old_type_id: 2,
      type: '1',
      old_type: '1',
      rule: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        deadline: [{
          required: true, message: '请选择工单截止时间', trigger: 'blur'
        }]
      },
      saleOrderTableData: [],
      centerDialogVisible: false,
      saleOrderTableLoading: false,
      saleListParams: {
        page: 1,
        page_size: 10
      },
      saleTableTotal: null,
      selectOrderTableData: [],
      buildingTableLoading: false,
      buildingTableData: [],
      selectBuildingTableData: [],
      buildingSearchForm: {
        page: 1,
        page_size: 10,
        work_order_type_id: 1,
        media_type_id: null,
        name: null,
        adcode: null
      },
      buildingListParams: {
        page: 1,
        page_size: 10,
        work_order_type_id: 1,
        media_type_id: null,
        name: null,
        adcode: null
      },
      buildingTotal: null,
      buildingDialogVisible: false,
      // selectBuildingIdList: [],
      selectSaleOrderId: null,
      selectMarketDetailId: null,
      assignWorkersDialogVisible: false,
      treeData: [],
      tmpList: [],
      buildingList: [],
      searchAreaVOList: [],
      media_type_arr: [],


	  saleOrderSearchForm:{
		  name: null
	  }
    }
  },
  methods: {
	  resetSaleOrderForm(){
		  this.saleOrderSearchForm.name = null;
		  this.getSaleOrderList();
	  },

    closeThisPage() {
      this.$store.dispatch('tagsView/closeCurPage')
    },
    async workOrderTypeChange(val) {
      let flag = true
      if (this.buildingList.length > 0 || this.tmpList.length > 0) {
        flag = await common.confirmDialog('切换类型将清空配置项')
      }
      if (flag) {
        this.tmpList = []
        this.buildingList = []
        this.buildingSearchForm.work_order_type_id = val
        this.old_type_id = val
        if (val == 4 || val == 2 || val == 3 || val == 7 || val == 8) {
          this.type = '1'
        } else {
          this.type = '2'
        }
      } else {
        this.cuForm.work_order_type_id = this.old_type_id
      }
    },
    async typeChange(val) {
      let flag = true
      if (this.buildingList.length > 0 || this.tmpList.length > 0) {
        flag = await common.confirmDialog('切换类型将清空配置项')
      }
      if (flag) {
        this.tmpList = []
        this.buildingList = []
        this.old_type = val
      } else {
        this.type = this.old_type
      }
    },
    showSaleOrderDialog() {
      this.centerDialogVisible = true
      this.getSaleOrderList()
    },
    getSaleOrderList() {
      this.saleOrderTableLoading = true
      const params = Object.assign({ work_order_type_id: this.cuForm.work_order_type_id }, this.saleListParams, {name: this.saleOrderSearchForm.name})
      listBillSale(params).then(res => {
        this.saleOrderTableLoading = false
        this.saleTableTotal = res.data.total
        this.saleOrderTableData = res.data.records
      })
    },
    saleTableCurrentChange(val) {
      this.saleListParams.page = val
      this.getSaleOrderList()
    },
    selectOrder(row) {
      this.selectOrderTableData.push(Object.assign({}, row))
      this.$confirm('确定使用此销售单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
        // type: 'warning'
      }).then(() => {
        this.chooseSaleOrder()
      }).catch(() => {
        this.selectOrderTableData = []
      })
    },
    removeOrder(index) {
      this.selectOrderTableData.splice(index, 1)
    },
    closeSaleOrderDialog() {
      this.saleListParams.page = 1
      this.selectOrderTableData = []
	    this.saleOrderTableData = []
	    this.saleOrderSearchForm = {name: null}
    },
    showBuildingDialog() {
      this.buildingDialogVisible = true
      this.buildingSearch()
    },
    closeBuildingDialog() {
      this.buildingSearchForm = {
        page: 1,
        page_size: 10,
        work_order_type_id: this.buildingSearchForm.work_order_type_id,
        media_type_id: null,
        name: null,
        adcode: null
      }
      this.buildingListParams = {
        page: 1,
        page_size: 10,
        work_order_type_id: this.buildingSearchForm.work_order_type_id,
        media_type_id: null,
        name: null,
        adcode: null
      }
      this.selectBuildingTableData = []
      this.buildingTableData = []
    },
    save() {
      this.$refs['cuForm'].validate((valid) => {
        this.cuForm.buidingSaveDTOS = []
        if (valid) {
          if ((this.cuForm.work_order_type_id == 1) || (this.cuForm.work_order_type_id == 4 && this.type == 2)) {
            this.buildingList.forEach(item => {
              let tmp = {
                id: item.id,
                workerIds: item.works.map(worker => {
                  return worker.id
                })
              }
              if (this.cuForm.work_order_type_id == 1) {
                tmp.new_install_mediaPoint = {}
                item.media_point.forEach(point => {
                  if (tmp.new_install_mediaPoint.hasOwnProperty(point.media_type_id)) {
                    tmp.new_install_mediaPoint[point.media_type_id] += point.select_num
                  } else {
                    tmp.new_install_mediaPoint[point.media_type_id] = point.select_num
                  }
                })
              } else {
                tmp.check_mediaPoint = {}
                item.media_point.forEach(point => {
                  if (tmp.check_mediaPoint.hasOwnProperty(point.media_type_id)) {
                    tmp.check_mediaPoint[point.media_type_id] = tmp.check_mediaPoint[point.media_type_id].concat(point.point_ids)
                  } else {
                    tmp.check_mediaPoint[point.media_type_id] = point.point_ids
                  }
                })
              }
              this.cuForm.buidingSaveDTOS.push(tmp)
            })
          } else {
            if (!this.edit) {
              this.cuForm.bill_sale_id = this.selectSaleOrderId
              this.cuForm.bill_market_detail_id = this.selectMarketDetailId
            }
            this.tmpList[0].dataArr.forEach(building => {
              this.cuForm.buidingSaveDTOS.push({
                id: building.id,
                workerIds: building.works.map(worker => {
                  return worker.id
                })
              })
            })
          }
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          if (this.edit) {
            edit(this.cuForm).then(res => {
              if (res.code == 200) {
                this.$message.success(res.data)
                this.closeThisPage()
              }
              loading.close()
            }).catch(() => {
              loading.close()
            })
          } else {
            save(this.cuForm).then(res => {
              if (res.code == 200) {
                this.$message.success(res.data)
                this.closeThisPage()
              }
              loading.close()
            }).catch(() => {
              loading.close()
            })
          }
        }
      })
    },
    buildingSearch() {
      this.buildingSearchForm.page = 1
      this.buildingListParams = Object.assign({}, this.buildingSearchForm)
      this.getBuildingList()
    },
    getBuildingList() {
      this.buildingTableLoading = true
      listPageBuilding(this.buildingListParams).then(res => {
        this.buildingTableLoading = false
        this.buildingTotal = res.data.total
        this.buildingTableData = res.data.records
      })
    },
    buildingTableCurrentChange(val) {
      this.buildingListParams.page = val
      this.getBuildingList()
    },
    selectBuilding(row) {
      this.selectBuildingTableData.push(Object.assign({}, row))
    },
    removeBuilding(index) {
      this.selectBuildingTableData.splice(index, 1)
    },
    chooseSaleOrder() {
      if (this.selectOrderTableData.length > 0) {
        this.selectSaleOrderId = this.selectOrderTableData[0].id
        this.selectMarketDetailId = this.selectOrderTableData[0].bill_market_detail_id
        let choose_id = this.selectOrderTableData[0].choose_id
        let daterange_id = this.selectOrderTableData[0].daterange_id
        this.centerDialogVisible = false
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        listBuildingOfBillSale({ bill_sale_id: this.selectSaleOrderId, choose_id, daterange_id }).then(res => {
          this.tmpList = formatDataToSale(res)
          // this.selectBuildingIdList = this.tmpList[0].dataArr.map(item => {
          //   return item.id
          // })
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    },
    chooseBuilding() {
      // this.selectBuildingIdList = this.selectBuildingTableData.map(item => {
      //   return item.id
      // })
      this.selectBuildingTableData.forEach(building => {
        building.media_point.forEach(item => {
          if (item.num == undefined) {
            this.$set(item, 'num', item.point_ids.length)
            this.$set(item, 'disabled', true)
          } else {
            this.$set(item, 'disabled', false)
          }
          this.$set(item, 'select_num', item.num)
        })
        if (building.works == undefined) {
          this.$set(building, 'works', [])
        }
      })
      this.buildingList = this.selectBuildingTableData
      this.buildingDialogVisible = false
    },
    showAssignWorkers() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.treeData = []
      let data = {
        id: -1,
        label: '常州市',
        children: [],
        is_leaf: false,
        disabled: false
      }
      let buildingWorkers = null
      if (this.type == 1) {
        buildingWorkers = getBuildingWorkers(this.tmpList)
      } else {
        buildingWorkers = this.buildingList.map(item => {
          return Object.assign({}, item)
        })
      }
      listBuildingMacthWorker(this.selectBuildingIdList).then(res => {
        res.data.forEach(item => {
          let children = []
          item.buildingAreaList.forEach(building => {
            let find = buildingWorkers.find(item => item.id == building.id)
            if (find) {
              children.push({
                  id: building.id,
                  label: building.name,
                  is_leaf: true,
                  children: [],
                  works: find.works,
                  disabled: false
                }
              )
            } else {
              children.push({
                  id: building.id,
                  label: building.name,
                  is_leaf: true,
                  children: [],
                  works: [],
                  disabled: false
                }
              )
            }
          })
          data.children.push({
            id: generateUUID(),
            label: item.area,
            children,
            is_leaf: false,
            disabled: false
          })
        })
        this.treeData.push(data)
        this.assignWorkersDialogVisible = true
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    closeAssignWorkersDialog() {
      this.assignWorkersDialogVisible = false
      this.treeData = []
    },
    saveAssignWorkers(buildingWorkers) {
      buildingWorkers.forEach(building => {
          let find = null
          if (this.type == 1) {
            find = this.tmpList[0].dataArr.find(item => item.id == building.id)
          } else {
            find = this.buildingList.find(item => item.id == building.id)
          }
          if (find) {
            find.works = building.works
          }
        }
      )
      this.closeAssignWorkersDialog()
    },
    /**
     * 改变所有的非叶子节点状态
     */
    changeAllNotLeafStatus(flag, data) {
      if (!data.is_leaf) {
        data.disabled = flag
      }
    },
    filterNode(value, data) {
      if (!value) {
        this.changeAllNotLeafStatus(false, data)
        return true
      } else {
        this.changeAllNotLeafStatus(true, data)
        return data.label.indexOf(value) !== -1
      }
    },
    replacePoint(source, target, building_id, index, media_type_id, vc) {
      const data = {
        work_order_id: this.cuForm.id,
        old_device_id: source.id,
        new_device_id: target.id
      }
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      replacePoint(data).then(res => {
        if (res.data) {
          let building = this.tmpList[index].dataArr.find(building => building.id == target.building_area_id)
          let source_building = this.tmpList[index].dataArr.find(building => building.id == building_id)
          if (building === undefined) {
            building = {}
            building.id = target.building_area_id
            building.name = target.building_area_name
            building.workers = source_building.workers
            building.works = source_building.works
            building.pointTypeCountVOMap = {}
            this.tmpList[index].arr.forEach(i => {
              if (i == media_type_id) {
                building.pointTypeCountVOMap[i] = {
                  mediaPointList: [target],
                  point_type_count: 1,
                  point_type_id: parseInt(i),
                  to: 1
                }
              } else {
                building.pointTypeCountVOMap[i] = {
                  mediaPointList: [],
                  point_type_count: 0,
                  point_type_id: parseInt(i),
                  to: 0
                }
              }
            })
            this.tmpList[index].dataArr.push(building)
            source_building.pointTypeCountVOMap[media_type_id].to -= 1
            let point_list = source_building.pointTypeCountVOMap[media_type_id].mediaPointList
            for (let i = 0; i < point_list.length; i++) {
              let point = point_list[i]
              if (point.id == source.id) {
                point_list.splice(i, 1)
                break
              }
            }
            // 删除所有类型点位都是0的楼盘数据
            let delete_building_ids = []
            for (let j = 0; j < this.tmpList[index].dataArr.length; j++) {
              let item = this.tmpList[index].dataArr[j]
              let flag = true
              for (let i = 0; i < this.tmpList[index].arr.length; i++) {
                if (item.pointTypeCountVOMap[this.tmpList[index].arr[i]].to != 0) {
                  flag = false
                  break
                }
              }
              if (flag) {
                delete_building_ids.push(item.id)
              }
            }
            this.tmpList[index].dataArr = this.tmpList[index].dataArr.filter(item => !delete_building_ids.includes(item.id))
          } else {
            let point_list = building.pointTypeCountVOMap[media_type_id].mediaPointList
            for (let i = 0; i < point_list.length; i++) {
              let point = point_list[i]
              if (point.id == source.id) {
                point_list.splice(i, 1, target)
                break
              }
            }
          }
          vc.drawer = false
          this.$nextTick(() => {
            if (vc.pointDataArr.length === 0) {
              vc.close()
            }
          })
        }
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    getDetail(params) {
      this.edit = true
      this.formLoading = true
      detail(params.id).then(res => {
        this.cuForm = res.data
        if (res.data.bill_sale_id != undefined) {
          this.type = '1'
        } else {
          this.type = '2'
        }
        if (params.type_id == 2 || params.type_id == 3 || params.type_id == 7 || params.type_id == 8 || (params.type_id == 4 && this.cuForm.bill_sale_id)) {
          this.tmpList = formatDataToSale(res)
        } else {
          res.data.buidingDetailVOS.forEach(building => {
            building.media_point.forEach(item => {
              if (item.num == undefined) {
                this.$set(item, 'num', (item.point_ids || []).length)
                this.$set(item, 'disabled', true)
              } else {
                this.$set(item, 'disabled', false)
              }
              this.$set(item, 'select_num', item.num)
            })
            if (building.workers != undefined) {
              this.$set(building, 'works', building.workers)
            } else {
              this.$set(building, 'works', [])
            }
          })
          this.buildingList = res.data.buidingDetailVOS
        }
        this.formLoading = false
      })
    },
    reload() {
      this.getDetail(this.$route.params)
    },
    // 获取地址分类
    selectSearchArea() {
      return selectSearchAreaVO()
        .then(res => {
          const {
            code,
            data
          } = res
          if (code == 200) {
            for (let i = 0; i < data.length; i++) {
              if (data[i] && data[i].adcode) {
                this.searchAreaVOList.push(data[i])
              }
            }
          }
        })
    },
    // 初始化媒体类型数据
    initMediaTypeArr() {
      get_media_types().then(res => {
        this.media_type_arr = res.data
      })
    },
    // 全选
    allSelect() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      allSelectBuildingList(this.buildingSearchForm).then(res => {
        res.data.forEach(item => {
          if (this.selectBuildingTableData.find(building => building.id === item.id) === undefined) {
            this.selectBuildingTableData.push(cloneDeep(item))
          }
        })
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    allRemoveBuilding() {
      this.$confirm('确定全部移除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectBuildingTableData = []
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped>
.page_main {
  width: 70%;
  margin: 40px auto;
}

.header {
  font-size: 25px;
  text-align: center;
  font-weight: bold;
  padding: 20px 0;
}

/deep/ .building {
  background-color: #e9f9ff !important;
}

/deep/ .building_header th {
  background-color: #e9f9ff !important;
}
</style>
